package com.zjzywl.iotSendthings.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zjzywl.iotSendthings.entity.CPicture;
import com.zjzywl.iotSendthings.entity.IdentityCard;
import com.zjzywl.iotSendthings.entity.JDWPBGMX;
import com.zjzywl.iotSendthings.entity.JDWPBGXX;
import com.zjzywl.iotSendthings.entity1.KSSRYJBXXB;
import com.zjzywl.iotSendthings.entity.WPJSZPB;
import com.zjzywl.iotSendthings.entity1.RYJBXXB;
import com.zjzywl.iotSendthings.repository.CPictureRepository;
import com.zjzywl.iotSendthings.repository.IdentityCardRepository;
import com.zjzywl.iotSendthings.repository.InsertJDWPBGMXRepository;
import com.zjzywl.iotSendthings.repository.InsertJDWPBGXXRepository;
import com.zjzywl.iotSendthings.repository.InsertWPJSZPBRepository;
import com.zjzywl.iotSendthings.repository1.PrisonerRepository;
import com.zjzywl.iotSendthings.util.Item;
import com.zjzywl.iotSendthings.util.WebResult;

@Controller
@RequestMapping(value = "/insert")
public class InsertInformationController {
    @Autowired
    private InsertJDWPBGXXRepository insertRepository;
    @Autowired
    private InsertJDWPBGMXRepository JDWPBGMXRepository;
    @Autowired
    private InsertWPJSZPBRepository WPJSZPBRepository;
    @Autowired
    private IdentityCardRepository repository;
    @Autowired
    private PrisonerRepository prisonerRepository;
    @Autowired
    private CPictureRepository CPrepository;
    // 看守所编号
    @Value("${app.kssbh}")
    private String kssbh;

    @Value("${spring.datasource.primary.url}")
    private String MysqlUrl;

    @Value("${spring.datasource.primary.username}")
    private String MysqlUsername;
    @Value("${spring.datasource.primary.password}")
    private String MysqlPassword;

    /*
     * 前台提交表单接口
     */
    @RequestMapping(value = "/information")
    @ResponseBody
    public WebResult registe1r(Item items, HttpServletRequest request) {
        String yzyrygx = items.getYzyrygx();
        String lxdh = items.getLxdh();
        String zjhm = items.getFxrysfz();
        String uuid = items.getUuid();

        List<RYJBXXB> prisoners = prisonerRepository.getName(zjhm);
        RYJBXXB name = prisoners.get(0);
        String jbxxbh = name.getJbxxbh();
        String zyryxm = name.getXm();
        KSSRYJBXXB jsh = prisonerRepository.getJsh(jbxxbh);
        String rybh = jsh.getRybh();

        Date Time = new Date();
        JDWPBGXX xx = new JDWPBGXX();
        String str = insertRepository.findZybh();

        SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
        String Str = format1.format(Time);
        String sub = Str.substring(1, Str.length());
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String eStr = format.format(Time);
        String zybh = "";
        if (str == null || str.indexOf(sub) == -1) {
            xx.setZybh(kssbh + sub + 1000);
            xx.setDjbh("2" + sub + 1000);
            zybh = kssbh + sub + 1000;
        } else {
            String substring = str.substring(str.length() - 4, str.length());
            int parseInt = Integer.parseInt(substring) + 1;
            xx.setZybh(kssbh + sub + parseInt);
            xx.setDjbh(Str + parseInt);
            zybh = kssbh + sub + parseInt;
        }

        IdentityCard ic = repository.findByUuid(uuid);
        xx.setRybh(rybh);
        xx.setSjc(eStr);
        xx.setSwrxm(ic.getName().trim());
        xx.setSwrzjh(ic.getCode());
        xx.setYzyrygx(yzyrygx);
        xx.setLxdh(lxdh);
        xx.setFxrysfz(zjhm);
        xx.setUuid(uuid);
        xx.setBglx("普通物品");
        xx.setLqbj("0");
        xx.setBgrq(eStr);
        xx.setSwrdz(ic.getAddress());
        xx.setJsfs("自助送物");
        xx.setZyryxm(zyryxm);
        insertRepository.save(xx);

        try {
            List<String> sl = items.getSl();
            List<String> wp = items.getWp();
            List<String> gg = items.getGg();

            for (int i = 0; i < sl.size(); i++) {
                String Mxzybh = JDWPBGMXRepository.findZybh();
                JDWPBGMX jd = new JDWPBGMX();

                jd.setSjc(eStr);
                jd.setBgzybh(zybh);
                if (Mxzybh == null || Mxzybh.indexOf(sub) == -1) {
                    jd.setZybh(kssbh + sub + 1000);
                } else {
                    String substring = Mxzybh.substring(Mxzybh.length() - 4, Mxzybh.length());
                    int parseInt = Integer.parseInt(substring);
                    ++parseInt;
                    jd.setZybh(kssbh + sub + parseInt);
                }
                jd.setUuid(uuid);
                jd.setWp(wp.get(i));
                jd.setSl(sl.get(i));
                jd.setNum(i + "");
                jd.setGg(gg.get(i));
                JDWPBGMXRepository.save(jd);
            }

        } catch (Exception e) {
            // TODO: handle exception
            return WebResult.FAIL("表单提交失败");
        }
        return WebResult.OK();

    }

    /*
     * 存储物品图片
     */
    @RequestMapping(value = "/saveThing")
    @ResponseBody
    public WebResult saveThing(HttpServletRequest request, HttpServletResponse response, HttpSession session)
            throws Exception {
        Date Time = new Date();
        String uuid = request.getParameter("uuid");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String eStr = format.format(Time);
        String tpid = request.getParameter("tpid");
        SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
        String Str = format1.format(Time);
        String sub = Str.substring(1, Str.length());
        Connection connection = null;
        String connectionURL = MysqlUrl;
        ResultSet rs = null;
        PreparedStatement psmnt = null;
        FileInputStream fis;

        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection(connectionURL, MysqlUsername, MysqlPassword);
            System.out.println("图片id" + tpid);
            CPicture cp = CPrepository.findByUuid(tpid);
            String pictureFile = cp.getFile();
            System.out.println("图片存储路径" + pictureFile);
            File image = new File(pictureFile);
            System.out.println(image);

            //try {
            JDWPBGXX findByuuid = insertRepository.findByuuid(uuid);
            System.out.println(findByuuid.getZybh());
            String zpzybh = WPJSZPBRepository.findZyzybh();
            System.out.println("图片的主键" + zpzybh);
            psmnt = connection
                    .prepareStatement("insert into wpjszpb (zpzybh,wpjszybh,zp,sjc,uuid) values (?,?,?,?,?) ");
            if (zpzybh == null || zpzybh.indexOf(sub) == -1) {
                psmnt.setString(1, kssbh + sub + 1000);
            } else {
                String substring = zpzybh.substring(zpzybh.length() - 4, zpzybh.length());
                int parseInt = Integer.parseInt(substring) + 1;
                psmnt.setString(1, kssbh + sub + parseInt);
            }
            psmnt.setString(2, findByuuid.getZybh());
            psmnt.setString(4, eStr);
            psmnt.setString(5, uuid);
            fis = new FileInputStream(pictureFile);
            psmnt.setBinaryStream(3, (InputStream) fis, (int) (image.length()));
            int s = psmnt.executeUpdate();
            if (s > 0) {
                System.out.println("物品拍照成功");
                return WebResult.OK();
            } else {
                System.out.println("物品拍照失败");
                return WebResult.FAIL("unsucessfull to upload image.");
            }
        } catch (Exception ex) {
            System.out.println("Found some error : " + ex);
            return WebResult.FAIL("unsucessfull to upload image.");
        } finally {
            // close all the connections.
            connection.close();
            psmnt.close();
        }

    }

    /*
     * 删除图片接口
     */
    @RequestMapping(value = "/delImg")
    @ResponseBody
    public void delImg(HttpServletRequest request) throws Exception {
        String zpzybh = request.getParameter("tpid");
        WPJSZPBRepository.del(zpzybh);
    }

    /*
     * 审批提交表单接口
     */
    @RequestMapping(value = "/approve")
    @ResponseBody
    public WebResult approve(Item items) {
        String yzyrygx = items.getYzyrygx();
        String lxdh = items.getLxdh();
        String fxrysfz = items.getFxrysfz();
        String uuid = items.getUuid();
        String sjc = items.getSjc();
        String bz = items.getBz();
        Date Time = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String eStr = format.format(Time);
        try {
            List<String> sl = items.getSl();
            List<String> wp = items.getWp();
            for (int i = 0; i < sl.size(); i++) {
                for (int j = 0; j < wp.size(); j++) {
                    JDWPBGMX jd = new JDWPBGMX();

                    jd.setSjc(eStr);
                    jd.setBgzybh(uuid + 1);
                    String zybh = insertRepository.findZYBH(uuid);
                    jd.setZybh(zybh);
                    jd.setUuid(uuid);
                    jd.setWp(wp.get(j));
                    jd.setSl(sl.get(i));
                    if (i == j) {
                        jd.setNum(i + "");
                        JDWPBGMXRepository.save(jd);
                    }
                }
            }

            insertRepository.updateApproveJDWPBGXX(yzyrygx, lxdh, fxrysfz, uuid, bz);
            WPJSZPB wj = new WPJSZPB();
            wj.setSjc(eStr);
            wj.setWpjszybh(uuid + 1);
            wj.setZpzybh(uuid + 1);
            WPJSZPBRepository.save(wj);
        } catch (Exception e) {
            // TODO: handle exception
            return WebResult.FAIL("表单提交失败");
        }
        return WebResult.OK();

    }

}
